
import * as mars3d from "mars3d"
// map的部分公共操作
import { proj4 } from "mars3d"
import { Cesium } from "mars3d";
import * as turf from "@turf/turf";
// image
import coordinatepng from '@/assets/mapicon/coordinate.png';
import linetrans from '@/assets/mapicon/linetrans.png';
import localforage from 'localforage';

// namespace缺失wgs84ToWindowCoordinates 和 worldToWindowCoordinates 相同
Cesium.SceneTransforms.wgs84ToWindowCoordinates = Cesium.SceneTransforms.worldToWindowCoordinates;

let defaultProjectExtend = [
  [106.474428,29.59634],
  [106.474428,29.578971],
  [106.533899,29.578971],
  [106.533899,29.59634],
  [106.474428,29.59634]
]

// 销毁map
export function destroyMap(map) {
  if (!map) {
    return
  }
  map.destroy()
  map = null
}


// center: { lat: 31.628661, lng: 117.251952, alt: 46390, heading: 2, pitch: -68,roll:}
// 飞向视点
export function flytoView(map, center) {
  map.setCameraView(center)
}

// 坐标转换
export function transform(coordinates) {
  proj4.defs("EPSG:4545", "+proj=tmerc +lat_0=0 +lon_0=108 +k=1 +x_0=500000 +y_0=0 +ellps=GRS80 +units=m +no_defs +type=crs");
  proj4.defs("WGS84", "+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs  ");
  const result = proj4("EPSG:4545", "WGS84", coordinates);
  return result
}
//笛卡尔空间直角坐标   转换为   地理坐标(经纬度)
export function transformCar(coordinates) {
  return coordinates.map((item)=>{
    const  {_lng,_lat,_alt} =  mars3d.LngLatPoint.fromCartesian(item)
    return {x: _lng, y: _lat,z: _alt};
  })
}

export class RandomData{
  
}

export class SptialAnalysis {

  static createPolygonFromList(list=defaultProjectExtend){
    return turf.polygon([list])
  }


  static randomPointFromPolygon(list=defaultProjectExtend){
    let polygon = this.createPolygonFromList(list);
    let points = turf.randomPoint(100, { bbox: turf.bbox(polygon)});
    return points
  }


}


export class LayerCreate {

  static async getClusterImage(count) {
    let colorIn
    if (count < 10) {
      colorIn = "rgba(110, 204, 57, 0.6)"
    } else if (count < 100) {
      colorIn = "rgba(240, 194, 12,  0.6)"
    } else {
      colorIn = "rgba(241, 128, 23,  0.6)"
    }

    const radius = 40
    const thisSize = radius * 2

    const circleCanvas = document.createElement("canvas")
    circleCanvas.width = thisSize
    circleCanvas.height = thisSize
    const circleCtx = circleCanvas.getContext("2d", { willReadFrequently: true })

    circleCtx.fillStyle = "#ffffff00"
    circleCtx.globalAlpha = 0.0
    circleCtx.fillRect(0, 0, thisSize, thisSize)

    // 圆形底色
    circleCtx.globalAlpha = 1.0
    circleCtx.beginPath()
    circleCtx.arc(radius, radius, radius, 0, Math.PI * 2, true)
    circleCtx.closePath()
    circleCtx.fillStyle = colorIn
    circleCtx.fill()

    // 数字文字
    const text = count + "个"
    circleCtx.font = radius * 0.6 + "px bold normal" // 设置字体
    circleCtx.fillStyle = "#ffffff" // 设置颜色
    circleCtx.textAlign = "center" // 设置水平对齐方式
    circleCtx.textBaseline = "middle" // 设置垂直对齐方式
    circleCtx.fillText(text, radius, radius) // 绘制文字（参数：要写的字，x坐标，y坐标）

    return circleCanvas.toDataURL("image/png") // getImage方法返回任意canvas的图片即可
  }

  static createGraphicLayer() {
    const singleDigitPins = {};
    let graphicLayer = new mars3d.layer.GraphicLayer({
      allowDrillPick: true, // 如果存在坐标完全相同的图标点，可以打开该属性，click事件通过graphics判断,
      clustering: {
        enabled: true,
        pixelRange: 20,
        minChanged: 0.01,
        addHeight: 1000,
        opacity: 0.5,
        getImage: async (count, result) => {
          const key = "type1-" + count // 唯一标识，不同图层需要设置不一样

          let image = singleDigitPins[key]
          if (image) {
            return image // 当前页面变量有记录
          }

          image = await localforage.getItem(key)
          if (image) {
            singleDigitPins[key] = image
            return image // 浏览器客户端缓存有记录
          }

          image = await this.getClusterImage(count) // 生成图片
          singleDigitPins[key] = image // 记录到当前页面变量，未刷新页面时可直接使用
          localforage.setItem(key, image) // 记录到浏览器客户端缓存，刷新页面后也可以继续复用

          return image
        }
      }
    })
    return graphicLayer;
  }
}

export class AddGraphic {

  static initGraphicManager(graphic) {
    // 绑定Popup
    graphic.on(mars3d.EventType.popupOpen, function (event) {
      const container = event.container // popup对应的DOM
      console.log("打开了popup", container)
    })
    graphic.bindPopup(this.getInnerHtml);

    graphic.bindContextMenu([
      {
        text: "删除对象[graphic绑定的]",
        icon: "fa fa-trash-o",
        callback: (e) => {
          const graphic = e.graphic
          if (graphic) {
            graphic.remove()
          }
        }
      }
    ])
  }

  static addDemoGraphic1(graphicLayer, coordinates,image=coordinatepng) {
    const graphic = new mars3d.graphic.BillboardEntity({
      position: coordinates,
      style: {
        image: image,
        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        clampToGround: true
      },
    })
    graphicLayer.addGraphic(graphic) // 还可以另外一种写法: graphic.addTo(graphicLayer)
    return graphic;
  }

  static addtransLine(graphicLayer, positionscoordinates) {
    const graphic = new mars3d.graphic.PolylineEntity({
      positions: positionscoordinates,
      style: {
        width: 8,
        clampToGround: true,
        materialType: mars3d.MaterialType.LineFlow,
        materialOptions: {
          color: "rgba(89,249,255,1)",
          image: linetrans,
          speed: 3,
        }
      },
      flyTo: true
    })
    graphicLayer.addGraphic(graphic)
    return graphic;
  }
}